01 / 05

How does database/sql handle connection pooling?

sql.DB is a connection pool, not a single connection. Configure pool size, idle connections, and connection lifetime to match your database's max_connections and service traffic patterns.

Connection pool configuration
Pool configuration guidelines
  1. 1

    MaxOpenConns: set to (Postgres max_connections / number_of_service_instances) - some buffer

  2. 2

    MaxIdleConns: should be less than MaxOpenConns; keep commonly-needed connections alive

  3. 3

    ConnMaxLifetime: prevents stale connections after DB restarts or network disruptions

  4. 4

    Always use QueryContext, ExecContext, BeginTx — never the non-context variants in production

  5. 5

    For high-performance workloads, consider pgxpool from jackc/pgx which has better pool control